import { createRouter, createWebHistory } from "vue-router";
import Login from "../views/Login.vue";
import Admin from "../views/admin/index.vue";
import { getMenus } from "./grants";
import {useMenus} from "@/stores/menus";
import type { IRouter } from "@/mytype";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      redirect: "/Login"
    },
    {
      path: "/Login",
      name: "Login",
      component: Login
    },
    {
      path: "/Admin",
      name: "Admin",
      component: Admin
    }
    // {
    //   path:'/:pathMatch(.*)*',
    //   component:import("../views/NotFound.vue")
    // }
  ]
});

// 处理权限和菜单
// 1、在刷新时，动态添加路由：并且把菜单获取到
let menus:IRouter[] = new Array<IRouter>();

if(sessionStorage.getItem("checkedKeys")){   
  
  console.log("刷新时，获取菜单，动态添加路由");
  
  menus =  getMenus(router);

}

// 路由守卫
router.beforeEach((to,from,next)=>{
  if(to.path=="/" || to.path=="/Login" ){
    next();
  }else{
    if(sessionStorage.getItem("username")){
      next();
    }else{
      next("/Login");
    }
  }
})

export default router;


// 处理权限和菜单
// 2、把获取的菜单保存在pinia里。

export const saveMenus=()=>{
   console.log("刷新时，把获取的菜单存储到pinia中");
    const menusStore = useMenus();
    menusStore.addMenus(menus);
}